package com.example.ordermealservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.commonutils.R;
import com.example.commonutils.handler.NoqueueException;
import com.example.ordermealservice.entity.OrderDish;
import com.example.ordermealservice.mapper.OrderDishMapper;
import com.example.ordermealservice.service.OrderDishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-06-13
 */
@Transactional
@Service
public class OrderDishServiceImpl extends ServiceImpl<OrderDishMapper, OrderDish> implements OrderDishService {

    @Autowired
    private OrderDishService orderDishService;
    @Override
    public void batchDelete(List<String> ids) {
        LambdaQueryWrapper<OrderDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OrderDish::getId,ids);
        orderDishService.remove(queryWrapper);
    }

    @Override
    public R subNumber(String dishId, Integer dishNumber) {
        LambdaQueryWrapper<OrderDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDish::getId,dishId);
        OrderDish one = orderDishService.getOne(queryWrapper);
        Integer newNumber = one.getDishNumber() - dishNumber;
        if (newNumber < 0){
//            one.setDishStatus(4);
            //这里为什么会回滚？
//            UPDATE order_dish SET dish_name=?, dish_picture=?, dish_price=?, dish_time=?, dish_number=?, dish_status=?, dish_classification=?, dish_subclassification=?, gmt_create=?, gmt_modified=?, version=? WHERE id=? AND version=?
//            铁锅炖大鹅(String), https://noqueue.oss-cn-nanjing.aliyuncs.com/0a5d6bc7-3b30-49ee-95e3-c48a108b6530Snipaste_2023-07-22_10-36-22.png(String), 0.01(BigDecimal), 40(Integer), 0(Integer), 4(Integer), 家常菜(String), 东北菜(String), 2023-07-22 10:53:26.0(Timestamp), 2023-07-27 15:26:46.328(Timestamp), 32(Integer), 1682584607851024386(String), 31(Integer)
//            orderDishService.updateById(one);//将订单状态改成异常
            return R.error().message("商品库存不足，请联系商家退款！");
        }
        one.setDishNumber(newNumber);
        boolean b = orderDishService.updateById(one);
        if (!b){
//            one.setDishStatus(4);
//            orderDishService.updateById(one);
            return R.error().message("商品库存不足，请联系商家退款！");
        }
        return R.ok();
    }
}
